import serial
from flask import Flask, request
import logging
import atexit
from datetime import datetime  # 添加导入时间模块

app = Flask(__name__)

# 配置串口
SERIAL_PORT = 'com6'
BAUD_RATE = 9600
TIMEOUT = 1

# 初始化串口连接
ser = None

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def open_serial():
    """打开串口"""
    global ser
    if ser is None or not ser.is_open:
        ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=TIMEOUT)
        logger.info("Serial port opened.")

def close_serial():
    """关闭串口"""
    if ser and ser.is_open:
        ser.close()
        logger.info("Serial port closed.")

# 在应用启动时打开串口
def initialize_serial():
    open_serial()

# 在应用退出时关闭串口
atexit.register(close_serial)

@app.route('/send-command', methods=['POST'])
def send_command():
    try:
        body = request.data.decode('utf-8')
        logger.info(f"Received command: {body}")

        if not ser.is_open:
            open_serial()

        # 判断是否为蜂鸣器开关指令
        if '{"command":"buzzer_switch"}' in body:
            ser.write('F'.encode('utf-8'))
        else:
            ser.write(body.encode('utf-8'))

        response = ser.read(100).decode('utf-8')
        logger.info(f"Received from serial: {response}")

        # 添加时间戳
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        response_with_timestamp = f"{timestamp} - {response}"

        return response_with_timestamp, 200
    except Exception as e:
        logger.error(f"Error: {e}")
        return "Error", 500

# 手动初始化串口
with app.app_context():
    initialize_serial()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, use_reloader=False)  # 禁用自动重启